package com.wangjw.controller;

import com.wangjw.common.Const;
import com.wangjw.pojo.User;
import com.wangjw.redis.RedisClient;
import com.wangjw.util.CookieUtil;
import com.wangjw.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by wangjw on 18/6/5.
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private RedisClient redisClient;

    // 登录
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login(String username, String password, HttpSession session, HttpServletResponse response) {
        User user = new User();
        user.setId(1);
        user.setUsername(username);
        user.setPassword(password);

        CookieUtil.writeLoginToken(response, session.getId());
        redisClient.setEx(session.getId(), JsonUtil.obj2String(user), Const.RedisCacheExtime.REDIS_SESSION_EXTIME);
        return "登录成功";
    }

    // 注销
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        String loginToken = CookieUtil.readLoginToken(request);
        CookieUtil.delLoginToken(request, response);
        redisClient.del(loginToken);
        return "注销成功";
    }
}
